package com.dm.cloud.core.config.rest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.time.Duration;

/**
 * @Author sg
 * @ClassName RestTemplateConfiguration.java
 * @Description 配置restTemplate
 * @Date 2021/08/19 13:53
 */
@Configuration
public class RestTemplateConfiguration {

    @Value("${rest.connect.timeout:10}")
    private Long connectTimeout;

    @Value("${rest.read.timeout:10}")
    private Long readTimeout;
    @Autowired
    CustomRestTemplateCustomizer customRestTemplateCustomizer;
    @Bean
    @LoadBalanced
    @ConditionalOnMissingBean(value = RestTemplate.class)
    public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) {
        RestTemplate restTemplate = restTemplateBuilder
                .setConnectTimeout(Duration.ofSeconds(connectTimeout))
                .setReadTimeout(Duration.ofSeconds(readTimeout))
//                .errorHandler(new TemplateResponseErrorHandler())
                .build();
        restTemplate.getMessageConverters().stream().filter(httpMessageConverter ->
                httpMessageConverter instanceof AbstractHttpMessageConverter).forEach(httpMessageConverter -> {
            ((AbstractHttpMessageConverter) httpMessageConverter).setDefaultCharset(StandardCharsets.UTF_8);
        });
        return restTemplate;
    }

    @Bean
    @DependsOn(value = {"customRestTemplateCustomizer"})
    public RestTemplateBuilder restTemplateBuilder() {
        return new RestTemplateBuilder(customRestTemplateCustomizer);
    }

}